package com.b2c.erp.controller;

import com.alibaba.fastjson.JSONObject;
import com.b2c.entity.api.ApiResult;
import com.b2c.common.utils.DateUtil;
import com.b2c.common.utils.ExpressClient;
import com.b2c.common.utils.JsonUtil;
import com.b2c.common.utils.MD5Utils;
import com.b2c.entity.datacenter.DcShopEntity;
import com.b2c.entity.douyin.DcDouyinAddressVo;
import com.b2c.entity.douyin.DcDouyinOrdersEntity;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.service.dou.DYOrderPullLogService;
import com.b2c.interfaces.ShopService;
import com.b2c.interfaces.dou.DouyinOrderService;
import com.b2c.interfaces.ScheduledService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;

import java.net.http.HttpResponse;
import java.util.*;

import static com.b2c.common.utils.HttpUtil.map2Url;

@Controller
public class ScheduledController {
    private static Logger log = LoggerFactory.getLogger(ScheduledController.class);
    @Autowired
    private ScheduledService scheduledService;
    @Autowired
    private DouyinOrderService douyinOrderService;
    @Autowired
    private ShopService shopService;
    @Autowired
    private DYOrderPullLogService dyOrderPullLogService;

    @Scheduled(cron = "0 0/60 * * * ?")//0 55 23 * * ?每天23点55分执行
    public void ffff() throws Exception {
        log.info("-----开始自动更新抖音订单-----");
//        updDyOrder();
        //log.info("-----结束自动更新抖音订单----");
    }

    //@Scheduled(cron = "0 5 0 * * ? ")//0 55 23 * * ?每天23点55分执行
    public void addWmsSalesData() {
        scheduledService.addWmsSalesData(DateUtil.customizeDate_(1));
    }

    public void updDyOrder() throws  Exception{
        Integer shopId = 8;
        Long endTime = System.currentTimeMillis() / 1000;//订单更新结束时间
        Long startTime = douyinOrderService.getDyOrderTime(shopId);//endTime-(60 * 60 * 24 * 1);//订单更新开始时间

        Integer pageIndex = 0;
        Integer pageSize=100;
        long addCount = 0;//新增的订单数
        long updCount = 0;//更新的订单数
        long errCount = 0;//错误的订单数
        ApiResult<Long[]> result=null;
        var shop = shopService.getShop(shopId);

        result = this.editDouyinOrder(startTime,endTime,shop,pageIndex,pageSize);

        if(result.getCode()>0) {
            log.info("自动拉取订单错误  "+ result.getMsg());
            return;
        }

        //计算总页数
        //计算总页数
        long totalSize = result.getData()[0];
        long totalPage = (totalSize % pageSize == 0) ? totalSize / pageSize : (totalSize / pageSize) + 1;
        addCount += result.getData()[1];
        updCount += result.getData()[2];
        errCount += result.getData()[3];
        log.info("拉取订单完成第  "+(pageIndex+1)+" 页,总共  "+totalPage+"  页");
        pageIndex++;
        if(totalPage > 1) {
            while (pageIndex < totalPage) {
                result = this.editDouyinOrder(startTime, endTime, shop, pageIndex, pageSize);
                addCount += result.getData()[1];
                updCount += result.getData()[2];
                errCount += result.getData()[3];
                log.info("拉取订单完成第  "+(pageIndex+1)+" 页,总共  "+totalPage+"  页");
                pageIndex++;

            }
        }
        String msg = "更新成功：总数："+totalSize+",新增："+addCount+",更新："+updCount+",错误："+errCount;
        //记录更新日志dc_douyin_order_pull_log
        dyOrderPullLogService.insertLog("ZD",1,(int)totalSize,DateUtil.stampToDateTime(startTime),DateUtil.stampToDateTime(endTime),msg);
        log.info(msg);
    }

    private ApiResult<Long[]> editDouyinOrder(Long startTime, Long endTime, DcShopEntity shop, Integer pageIndex, Integer pageSize) throws Exception{
        try {
            long totalOrder=0;//拉取到的总订单数
            long addCount =0;//新增的订单数
            long updCount = 0;//更新的订单数
            long errCount = 0;//错误的订单数

            String appKey = shop.getAppkey();
            String appSercet = shop.getAppSercet();

            String method = "order.searchList";

            String  sendUrl= "http://openapi.jinritemai.com/order/searchList";

            LinkedHashMap<String, Object> jsonMap =new LinkedHashMap<>();
            jsonMap.put("combine_status","{\"order_status\":2}");
            jsonMap.put("create_time_end",endTime);//截至时间
            jsonMap.put("create_time_start",startTime);//开始时间trade_type
            jsonMap.put("order_asc","true");
            jsonMap.put("page",pageIndex);//查询的第几页,默认值为0, 第一页下标从0开始
            jsonMap.put("size",pageSize);//每页大小 默认为10, 最大100


            JSONObject jsonObject = new JSONObject(true);
            jsonObject.putAll(jsonMap);

            String paramJson =jsonObject.toJSONString();
            String timestamp = DateUtil.dateToString(new Date(),"yyyy-MM-dd HH:mm:ss");
            String accessToken =shop.getSessionKey();
            String signStr = "app_key"+appKey+"method"+method+"param_json"+paramJson+"timestamp"+timestamp+"v"+"2";
            signStr = appSercet+signStr+appSercet;


            String sign = MD5Utils.stringToMD5(signStr);


            Map<String, String> params = new HashMap<>();
            params.put("app_key", appKey);
            params.put("access_token",accessToken);
            params.put("method", method);
            params.put("param_json",paramJson);
            params.put("timestamp", timestamp);
            params.put("v", "2");
            params.put("sign", sign);
            HttpResponse<String> response = ExpressClient.doPost(sendUrl, map2Url(params));
            JSONObject obj = JSONObject.parseObject(response.body());
            if(!obj.getString("err_no").equals("0")) return new ApiResult<>(EnumResultVo.DataError.getIndex(), obj.getString("message"));
            var resObj = obj.getJSONObject("data");
            if(resObj.getLong("total").intValue()==0)return new ApiResult<>(EnumResultVo.DataError.getIndex(),"无订单可以更新");
            var jsonArray= resObj.getJSONArray("shop_order_list");
            for(var json:jsonArray){
                var jsonTemp=(JSONObject)json;

                DcDouyinOrdersEntity douYinOrder= JsonUtil.strToObject(jsonTemp.toJSONString(),DcDouyinOrdersEntity.class);
                //queryOrderDetail(douYinOrder.getOrderId());
                if(jsonTemp.getJSONArray("logistics_info").size()>0){
                    var objTemp = (JSONObject)jsonTemp.getJSONArray("logistics_info").get(0);
                    douYinOrder.setLogisticsCode(objTemp.getString("tracking_no"));
                    douYinOrder.setLogisticsCompany(objTemp.getString("company_name"));
                }
                var address = JsonUtil.strToObject(douYinOrder.getPostAddr(), DcDouyinAddressVo.class);
                douYinOrder.setProvince(address.getProvince().getName());
                douYinOrder.setCity(address.getCity().getName());
                douYinOrder.setTown(address.getTown().getName());
                douYinOrder.setStreet(address.getStreet().getName());
                douYinOrder.setEncryptDetail(address.getEncryptDetail());
                if(douYinOrder.getOrderStatus()==2){
                    String phoneKey=douYinOrder.getEncrypt_post_tel().substring(0,douYinOrder.getEncrypt_post_tel().indexOf("$",douYinOrder.getEncrypt_post_tel().indexOf("$")+1));
                    douYinOrder.setPhoneKey(phoneKey+"$");
                    String addressKey=address.getEncryptDetail().substring(0,address.getEncryptDetail().indexOf("#",address.getEncryptDetail().indexOf("#")+1));
                    douYinOrder.setAddressKey(addressKey+"#");
                }
                var res = douyinOrderService.editDouYinOrder(douYinOrder,1);
                String[] arr = {douYinOrder.getOrderId(),douYinOrder.getProvince(),(douYinOrder.getOrderAmount() /100)+"",douYinOrder.getOrderStatus().toString(),douYinOrder.getCancelReason()};
                if(res.getCode() == EnumResultVo.SUCCESS.getIndex()) {

                    log.info("自动拉取数据，新增" + Arrays.toString(arr));
                    addCount++;
                }
                else if(res.getCode() == EnumResultVo.DataExist.getIndex()){
                    log.info("自动拉取数据，更新"+Arrays.toString(arr));
                    updCount++;
                }else {
                    log.info("自动拉取数据，"+douYinOrder.getOrderId() + "更新异常" + res.getMsg());
                    errCount++;
                }

//                if(res.getCode()>0)log.info(douYinOrder.getOrderId()+"更新异常"+res.getMsg());
            }
            totalOrder = resObj.getLong("total");
            Long[] data = {totalOrder,addCount,updCount,errCount};

            return new ApiResult<>(EnumResultVo.SUCCESS.getIndex(), "SUCCESS",data);
//            return new ApiResult<>(EnumResultVo.SUCCESS.getIndex(), "SUCCESS",resObj.getLong("total"));
        } catch (Exception e) {
            return new ApiResult<>(EnumResultVo.Fail.getIndex(), "系统异常："+e.getMessage());
        }
    }
}
